#include "FallingBlocks.h"
#include <math.h>

const ds::Rect FB_RECT = ds::Rect(80,370,70,70);
const float FB_SPAWN_TIMER = 0.5f;

void FallingBlocks::update(float elapsed) {
	emitBlocks(elapsed);
	clear();
	uint32 cnt = 0;
	while ( cnt < m_Blocks.num() ) {
		Block* b = &m_Blocks[cnt];
		b->timer += elapsed;
		float sz = b->size.x + (b->size.x * sin(b->timer*b->frequency)*b->amplitude);
		b->pos.addScale(b->velocity,elapsed);
		if ( b->pos.y < 700.0f ) {
			add(b->pos.x,b->pos.y,sz,sz,FB_RECT);
			++cnt;
		}
		else {
			m_Blocks.removeIndex(cnt);
		}
	}
	rebuild();
}

void FallingBlocks::emitBlocks(float elapsed) {
	m_Timer += elapsed;
	if ( m_Timer > FB_SPAWN_TIMER ) {
		m_Timer = 0.0f;
		Block b;
		float x = gEngine->random(50.0f,950.0f);
		float y = gEngine->random(50.0f,700.0f);
		b.pos = ds::Vec2(x,y);
		float angle = gEngine->random(0.0f,360.0f);
		b.velocity = ds::math::getRadialVelocity(angle,50.0f);
		float size = gEngine->random(10.0f,30.0f);
		b.size = ds::Vec2(size,size);
		b.timer = 0.0f;
		b.amplitude = gEngine->random(0.2f,0.8f);
		b.frequency = gEngine->random(0.5f,1.2f);
		m_Blocks.append(b);
	}
}


